<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">>新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" width="50" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="员工头像" prop="staffPhoto">
            <template #default="{row}" width="100">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                style="width:100%"
                :src="row.staffPhoto"
                alt=""
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formatData(row.formOfEmployment) }}
              <!-- {{ row.formOfEmployment=1?'正式':'非正式' }} -->
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <!-- 以查询参数传参 -->
              <!-- <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?userId=${row.id}`)"
              >查看</el-button> -->
              <!-- 以路基参数传参 -->
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :total="total"
            layout="prev, pager, next"
            :page-size="size"
            :current-page="page"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog v-if="showDialog" title="新增员工" :visible.sync="showDialog">
        <addor-edit
          @success="hSuccess"
          @close="showDialog=false"
        />
      </el-dialog>
      <!-- 生成二维码图片 -->
      <el-dialog title="生成二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <!-- 画布用来生成二维码 -->
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <el-dialog :visible.sync="showDialogRole" title="分配角色">
        <assign-role
          v-if="showDialogRole"
          :id="curId"
          @success="showDialogRole=false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import AssignRole from './assignRole'
import { getEmployeesList, delEmployees } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import addorEdit from './empDialog'
import QRCode from 'qrcode'
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// 使用累加器处理枚举数据
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    'addor-edit': addorEdit,
    AssignRole
  },
  data() {
    return {
      list: [],
      page: 1,
      size: 5,
      total: 0,
      showDialog: false,
      showCodeDialog: false, // 用来控制二维码显示和隐藏
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.loadEmployees()
    // console.log(employeesEnum)
  },
  methods: {
    hAssignRole(id) {
      this.showDialogRole = true
      this.curId = id
    },
    showCode(url) {
      if (url) {
        this.showCodeDialog = true
        // 生成二维码
        this.$nextTick(() => {
          const canvas = this.$refs.myCanvas
          QRCode.toCanvas(canvas, url)
        })
      }
    },
    exportExcel() {
      const { tHeader, data } = this.transZhKeyToexcel(this.list)
      // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then(excel => {
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // console.log(list, 'listaaaaaaaaaaaaaaaaaaaa')
        // const data = this.formatJson(filterVal, list)
        // console.log(data, 'dataaaaaaaaaaaaaaaaa') // [[1,'三体','刘慈欣',100000,'2022-11-05'],[2,'西游记','吴承恩',100000,'1995-11-05']]
        // const data = [[1, '三体', '刘慈欣', 100000, '2022-11-05'], [2, '西游记', '吴承恩', 100000, '1995-11-05']]
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    transZhKeyToexcel(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })
      const data = list.map(item => {
        return Object.values(item)
      })
      return { tHeader, data }
    },
    // 删除
    hDel(id) {
      this.$confirm('确定删除该部门吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployees(id)
        if (res.code === 10000) {
          this.$message.success(res.message)
          if (this.list.length === 1) {
            this.page--
          }
          this.loadEmployees()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    hSuccess() {
      this.showDialog = false
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployees()
    },
    formatData(id) {
      // 引入枚举文件处理数据返回结果渲染页面
      // return employeesEnum.hireType.find(item => item.id === id).value
      return hireType[id] || '未知'
    },
    async  loadEmployees() {
      try {
        const res = await getEmployeesList({ page: this.page, size: this.size })
        // console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }

  }
}
</script>
